package com.learning.netease.optimize.trx.orderservice.service;

import com.alibaba.fastjson.JSONObject;
import com.learning.netease.optimize.trx.orderservice.dao.OrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * ClassName: OrderService
 * Description: 订单服务
 * Date: 2019/1/30 14:54 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    /**
     * 创建订单
     *
     * @param orderInfo
     * @throws Exception
     */
    public void createOrder(JSONObject orderInfo) throws Exception {

        // 1. 订单信息 - 插入订单系统，订单数据库（事务-1）
        orderDao.saveOrder(orderInfo);

        // 2. 通过Http 接口发送订单信息到 运单系统
        String result = callDispatchApi(orderInfo);

        if (!Objects.equals("ok", result)) {
            throw new Exception("创建订单失败，原因【运单接口调用失败】");
        }

    }

    /**
     * 调用接口
     *
     * @param orderInfo
     * @return
     */
    private String callDispatchApi(JSONObject orderInfo) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 连接超时时间 > 3秒
        requestFactory.setConnectTimeout(3000);
        // 处理超时时间 > 2秒
        requestFactory.setReadTimeout(2000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://127.0.0.1:8080/dispatch?orderId=" + orderInfo.getString("orderId");
        return restTemplate.getForObject(url, String.class);
    }
}
